//
//  UIColor+Ex.swift
//  
//
//  Created by tank on 2021/9/29.
//

import Foundation
import UIKit
import LibBase

extension Extension where Base == UIColor {
    
    /// Initializers for creating colors
    /// - Parameters:
    ///   - R: Red 0-255
    ///   - G: Green 0-255
    ///   - B: Blue 0-255
    /// - Returns: UIColor
    static public func color(R: Int, G: Int, B: Int) -> UIColor {
        return UIColor(red: CGFloat(Float(R) / 255.0),
                       green: CGFloat(Float(G) / 255.0),
                       blue: CGFloat(Float(B) / 255.0), alpha: 1.0)
    }
    
    /// Initializers for creating colors
    /// - Parameters:
    ///   - R: Red 0-255
    ///   - G: Green 0-255
    ///   - B: Blue 0-255
    ///   - A: Alpha 0-255
    /// - Returns: UIColor
    static public func color(R: Int, G: Int, B: Int, A: Int) -> UIColor {
        return UIColor(red: CGFloat(Float(R) / 255.0),
                     green: CGFloat(Float(G) / 255.0),
                     blue: CGFloat(Float(B) / 255.0),
                     alpha: CGFloat(Float(A) / 255.0))
    }
    
    /// Initializers for creating colors
    /// - Parameter hex: 16进制字符串，#RRGGBB、#AARRGGBB
    /// - Returns: UIColor
    static public func color(hex: String) -> UIColor {
        
        var cString = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()

        if cString.hasPrefix("#") {
            cString.remove(at: cString.startIndex)
        }

        var rgbValue: UInt32 = 0
        Scanner(string: cString).scanHexInt32(&rgbValue)
        
        lazy var color1 = color(R: Int((rgbValue & 0x00FF0000) >> 16),
                                    G: Int((rgbValue & 0x0000FF00) >> 8),
                                    B: Int(rgbValue & 0x000000FF),
                                    A: Int((rgbValue & 0xFF000000) >> 24))
        
        lazy var color2 = color(R: Int((rgbValue & 0xFF0000) >> 16),
                                   G: Int((rgbValue & 0x00FF00) >> 8),
                                   B: Int(rgbValue & 0x0000FF))

        return cString.count == 8 ? color1 : color2
    }

    public var hexRGB: String {
        var r: CGFloat = 0
        var g: CGFloat = 0
        var b: CGFloat = 0
        var a: CGFloat = 0

        base.getRed(&r, green: &g, blue: &b, alpha: &a)

        return String(format: "#%02x%02x%02x", Int(r * 255), Int(g * 255), Int(b * 255))
    }

    public var hexARGB: String {
        var r: CGFloat = 0
        var g: CGFloat = 0
        var b: CGFloat = 0
        var a: CGFloat = 0

        base.getRed(&r, green: &g, blue: &b, alpha: &a)

        return String(format: "#%02x%02x%02x%02x", Int(a * 255), Int(r * 255), Int(g * 255), Int(b * 255))
    }
}
